var EventProxy = require('eventproxy');

var mongoose = require('./db.js');

var ancmtSchema = mongoose.Schema({
    publisher: {
        type: String,
        require: true
    },
    title: {
      type: String,
      require: true
    },
    content: {
        type: String,
        require: true
    },
    time: {
        type: String,
        require: true
    }
});

var Ancmt = mongoose.model('announcement', ancmtSchema);

var ancmtDAO = function () {};

ancmtDAO.prototype.addAncmt = function (title, content, callback) {
    var tempAncmt = new Ancmt();
    tempAncmt.publisher = "管理员"; // 先写死，实现功能后再改
    tempAncmt.title = title;
    tempAncmt.content = content;
    tempAncmt.time = (new Date()).valueOf();

    tempAncmt.save(callback);

};

ancmtDAO.prototype.findOne = function (callback) {
    Ancmt.count({}, function (e, count) {
        if(e){
            console.log(e);
            return callback(0);
        }
        if(count == 0){
            return callback(0);
        } else {
            var n = Math.floor(count*Math.random());
            Ancmt.find().skip(n).limit(1).lean().exec(function (e, ancmt){
                if(e){
                    return callback(0);
                } else {
                    return callback(ancmt[0]);
                }
            });
        }
    });
}

ancmtDAO.prototype.findAll = function(callback){
    Ancmt.find({},callback);
};

ancmtDAO.prototype.deleteOne = function (id, callback) {
    Ancmt.remove({_id: id}, callback);
}

module.exports = new ancmtDAO();
